package com.cx.core.redis.aspect;

import com.cx.core.common.constant.ErrorEnum;
import com.cx.core.common.exception.ServiceException;
import com.cx.core.redis.annotion.LockAnnotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
@Order(1)
public class DistributedLockAspect {

    private static final Logger log = LoggerFactory.getLogger(DistributedLockAspect.class);
    @Autowired
    private  RedissonClient redissonClient;

    @Around("@annotation(com.cx.core.redis.annotion.LockAnnotation)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LockAnnotation lockAnnotation = method.getAnnotation(LockAnnotation.class);
        String lockKey = lockAnnotation.preKey();
        RLock rLock = redissonClient.getLock(lockKey);
        Boolean lock = rLock.tryLock(5, TimeUnit.SECONDS);
        if (lock != null && lock) {
            try {
                return joinPoint.proceed();
            } finally {
                rLock.unlock();
            }
        }
        // 如果没有获取到锁，可以选择等待或者抛出异常
        throw new ServiceException(ErrorEnum.SYSTEM_BUSY);
    }
}